package com.hsmw.common.util;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MapUtil {

	private static String key = "1162a0493523cd474818d7d5dc81b77a";

	/**
	 *  用户所有的订单的抢单信息，这个对象存储是安全的
	 */
	private static ConcurrentHashMap<String, URLConnection> orderPool = new ConcurrentHashMap<String, URLConnection>();



	/**
	 * 高德api 根据地址获取经纬度
	 *
	 * @param name
	 * @return
	 */
	public static String getLatAndLogByName(String name) {
		log.info("进入高德地图的查询");
		log.info("进入高德地图的查询");
		String add = "";
		StringBuffer s = new StringBuffer();
		s.append("key=" + key + "&address=" + name);
		String res = sendPost("http://restapi.amap.com/v3/geocode/geo", s.toString());
		JSONObject jsonObject = JSONObject.fromObject(res);
		log.info("结束查询");
		JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("geocodes"));
		if (jsonArray != null && jsonArray.size() > 0) {
			JSONObject location = (JSONObject) jsonArray.get(0);
			add = location.get("location").toString();
		}
		log.info("结束");
		return add;
	}


	/**
	 * //返回起始地startAddr与目的地endAddr之间的距离，单位：米
	 *
	 * @param startLonLat
	 * @param endLonLat
	 * @return
	 */
	public static JSONArray getDistance(String startLonLat, String endLonLat) {
		//返回起始地startAddr与目的地endAddr之间的距离，单位：米
		String result = "";
		String queryUrl = "http://restapi.amap.com/v3/distance?key=" + key + "&origins=" + startLonLat + "&destination=" + endLonLat + "&type=1";
		String queryResult = getResponse(queryUrl);
		JSONObject jo = JSONObject.fromObject(queryResult);
		JSONArray ja = jo.getJSONArray("results");
		return ja;
	}



	private static String getResponse(String serverUrl) {
		//用JAVA发起http请求，并返回json格式的结果
		StringBuffer result = new StringBuffer();
		try {
			URL url = new URL(serverUrl);
			URLConnection conn = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
			in.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result.toString();
	}


	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url   发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			log.info("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url   发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, Map<String, Object>  param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");

			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			log.info("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 用SimpleDateFormat计算时间差
	 *
	 * @throws ParseException
	 */
	public static void calculateTimeDifferenceBySimpleDateFormat() throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Date parse = format.parse("20180322151111");
		Date date = format.parse("20180323141111");
		long between = date.getTime() - parse.getTime();
		long day = between / (24 * 60 * 60 * 1000);
		long hour = (between / (60 * 60 * 1000) - day * 24);
		long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		System.out.println(day + "天" + hour + "小时" + min + "分" + s + "秒");
	}


}
